package com.hugy.redis.controller;

import com.alibaba.fastjson.JSONObject;
import com.hugy.redis.config.AccessAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;

import static com.hugy.redis.config.Constants.CURRENT_PROVINCE_LIST;

@RequestMapping("/redis")
@AccessAnnotation("redis")
@RestController
public class RedisController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/test")
    @ResponseBody
    public ArrayList<String> test(){
        return CURRENT_PROVINCE_LIST;
    }

    @PostMapping("/add")
    public String add(String province, String city){
        JSONObject json = new JSONObject();
        ArrayList list = new ArrayList();
        list.add("北京");
        list.add("上海");
        list.add("温州");
        json.put("province",province);
        json.put("city", city);
        json.put("cityList", list);
        if(!redisTemplate.hasKey(province+"-"+city)){
            redisTemplate.opsForValue().set(province+"-"+city, json);
        }
        return "ok";
    }

    @GetMapping("/get")
    @ResponseBody
    public ArrayList<String> select(String province, String city){
        JSONObject json = (JSONObject)redisTemplate.opsForValue().get(province + "-" + city);
        if(json.get("cityList") != null){
            CURRENT_PROVINCE_LIST.addAll((ArrayList)json.get("cityList"));
        }
        return CURRENT_PROVINCE_LIST;
    }
}
